// pages/addoppUnit/addoppUnit.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import api from '../../utils/api';
import util from '../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    draftID: '', //汇票id
    searchValue: '', // 搜索值
    nodata: false, //是否没有数据
    tips: '暂无数据',
    loading: true,
    remind: '下拉加载更多',
    page: 1, // 当前页码
    pageSize: 10, // 每页显示数据
    buttoned: false, //防止用户多次点击，添加数据
    draftoppUnitList: [], //汇票列表数据
    result: [], //选择的要关联的汇票
    showCalendar: false,
    columns: [],
    leibieName: '', //选中的类别筛选项
    getLeibieList: [],
    totalInvMoney: 0,
  },
  onOpened() {
    const query = wx.createSelectorQuery();
    query.select('#calendar').boundingClientRect();
    query.exec((res) => {
      console.log(res); //这个节点距离顶部的距离   和距离底部的距离
    })
    console.log("日历打开")
  },
  //时间筛选--取消
  shijiaCenle() {
    this.selectComponent('#search1').toggle();
    console.log(this.data.startDate)
    console.log(this.data.endDate)
    this.setData({
      value1: '',
      startDate: '',
      endDate: '',
    })
    this.clearData()
  },
  //时间筛选--确认
  shijiaOk() {
    this.selectComponent('#search1').toggle();
    console.log(this.data.startDate, this.data.startDate, '时间筛选 : 开始时间 - 结束时间')
    if (this.data.startDate && this.data.startDate) {
      console.log('不为空')
      this.setData({
        startTimeStr: new Date(this.data.startDate).getTime(),
        endTimeStr: new Date(this.data.endDate).getTime(),
        value1: this.data.startDate + '~' + this.data.endDate,
      })
      this.clearData()
    }
  },
  //开始时间-结束时间
  onDisplay() {
    this.setData({
      date: this.formatDate(new Date()),
      minDate: new Date(new Date().getFullYear(), 0, 1).getTime(),
      maxDate: new Date(new Date().getFullYear() + 2, -1, 31).getTime(),
      showCalendar: true
    });
  },
  onClose() {
    this.setData({
      showCalendar: false
    });
  },
  formatDate(date) {
    date = new Date(date);
    let month = date.getMonth() + 1
    let day = date.getDate()
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }
    return `${date.getFullYear()}-${month}-${day}`;
  },
  onConfirmCalendar(event) {
    const [start, end] = event.detail;
    this.setData({
      showCalendar: false,
      startDate: this.formatDate(start),
      endDate: this.formatDate(end)
    });
  },
  //金额筛选--取消
  moneyCenle() {
    this.selectComponent('#search2').toggle();
    console.log(this.data.startMoney)
    console.log(this.data.endMoney)
    this.setData({
      value2: '',
      startMoney: '',
      endMoney: '',
    })
    this.clearData()
  },
  //金额筛选--确认
  moneyOk() {
    this.selectComponent('#search2').toggle();
    console.log(this.data.startMoney, this.data.endMoney, '金额筛选 : 金额筛选111 - 金额筛选222')
    if (this.data.startMoney && this.data.endMoney) {
      console.log('不为空')
      this.setData({
        startMoney: this.data.startMoney,
        endMoney: this.data.endMoney,
        value2: this.data.startMoney + '~' + this.data.endMoney,
      })
      this.clearData()
    }
  },
  onfieldstartMoneyChange(e) {
    this.setData({
      startMoney: e.detail
    })
  },
  onfieldendMoneyChange(e) {
    this.setData({
      endMoney: e.detail
    })
  },
  //类别列表
  leibieOpen(e) {
    this.setData({
      getLeibieList: [{
          dictValue: '银行承兑汇票',
          dictKey: 0
        },
        {
          dictValue: '商业承兑汇票',
          dictKey: 1
        },
      ],
    })
    console.log(this.data.getLeibieList)
  },
  clickItem(e) {
    console.log(e, e.currentTarget.dataset.filtertype)
    this.setData({
      leibieName: e.currentTarget.dataset.filtertype,
    })
  },
  //类别筛选--取消
  leibieCenle() {
    this.selectComponent('#search3').toggle();
    this.setData({
      value3: '',
      leibieName: '',
    })
    this.clearData()
  },
  //类别筛选--确认
  leibieOk() {
    this.selectComponent('#search3').toggle();
    console.log(this.data.leibieName)
    if (this.data.leibieName) {
      console.log('不为空')
      this.setData({
        leibieName: this.data.leibieName,
        value3: this.data.leibieName,
      })
      this.clearData()
    }
  },


  // 搜索
  onSearch(event) {
    this.setData({
      searchValue: event.detail && event.detail.value ? event.detail.value : event.detail,
    })
    this.clearData()
  },
  // 清空数据并重新加载数据
  clearData() {
    this.setData({
      draftoppUnitList: [],
      page: 1,
      loading: true,
      nodata: false,
      tips: '暂无数据'
    })
    this.getData()
  },
  //关联汇票 列表
  getData() {
    let that = this
    console.log(this.data.page, 'page')
    api.draftaddoppUnitList({
      data: {
        fkId: this.data.draftID,
        searchStr: that.data.searchValue ? that.data.searchValue : '',
        pageNum: this.data.page,
        pageSize: that.data.pageSize,
        startTime: that.data.startDate ? that.data.startDate : '',
        endTime: that.data.endDate ? that.data.endDate : '',
        startMoney: that.data.startMoney ? that.data.startMoney : '',
        endMoney: that.data.endMoney ? that.data.endMoney : '',
        lb: that.data.leibieName ? that.data.leibieName : '',
      },
      success: function (res) {
        console.log(res.data.data, "添加关联汇票列表")
        if (res.data.code == 200) {
          if (res.data.data.list.length > 0) {
            for (let i = 0; i < res.data.data.list.length; i++) {
              res.data.data.list[i].receiveMoney = util.formatFigure(res.data.data.list[i].receiveMoney)
            }
            that.data.totalPage = res.data.data.totalPage
            that.setData({
              draftoppUnitList: that.data.draftoppUnitList.concat(res.data.data.list),
              loading: false,
              nodata: false,
              remind: res.data.data.totalPage > res.data.data.pageNum ? '下拉加载更多' : '已经到底啦～',
              totalInvMoney: that.addComma(res.data.data.totalInvMoney)
            })
          } else {
            that.setData({
              nodata: true
            })
          }
        }
      }
    })
  },
  //千分位 转换
  addComma(date) {
    let str = '';
    let num = '';
    let newStr = '';
    date = date + '';
    if (date.indexOf('.') != -1) {
      num = date.split('.')[0]
      str = date.split('.')[1]
    } else {
      num = date
    }
    newStr = num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    newStr = str == '' ? newStr : newStr + '.' + str;
    return newStr;
  },
  //选择关联汇票
  onChange(event) {
    console.log(event, '选择的关联汇票')

    console.log(event.detail, '选择的关联汇票')
    this.setData({
      result: event.detail
    })
  },
  //确认
  onConfirm() {
    if (this.data.result.length > 0) {
      //添加关联汇票提交
      api.draftaUnitLinMulti({
        method: 'POST',
        data: {
          fkId: this.data.draftID,
          coId: this.data.coId,
          userId: this.data.unitId,
          idStr: this.data.result.toString()
        },
        success: function (res) {
          console.log(res.data.data, "添加关联汇票提交")
          if (res.data.code == 200) {
            wx.showToast({
              title: '添加成功',
            })
            //返回到上一页
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 50);
          }
        }
      })
      this.setData({
        buttoned: true,
      });
    } else {
      wx.showModal({
        content: '请选择要关联的汇票',
        showCancel: false,
        confirmColor: '#0041C4'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    this.setData({
      draftID: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      coId : wx.getStorageSync('userInfo').coId,
      unitId : wx.getStorageSync('userInfo').unitId
    })
    this.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.totalPage > this.data.page) {
      ++this.data.page;
      this.setData({
        loading: true
      })
      this.getData()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})